<template>
  <div class="wx-invite">
    <WeixinHeader :title="$route.meta.title" :page-alert="$t('all.autotext1202')"></WeixinHeader>
    <div class="wx-invite__content">
      <div class="sub-title">{{ $t('all.autotext671') }}</div>
      <a-form class="wx-invite__form" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-item :label="$t('all.autotext211')">
          <a-input readOnly :value="proName"></a-input>
        </a-form-item>
        <a-form-item :label="$t('all.autotext992')">
          <a-input readOnly :value="proNo"></a-input>
        </a-form-item>
      </a-form>
      <div class="sub-title">{{ $t('all.autotext425') }}</div>
      <a-form-model
        class="wx-invite__form"
        ref="subjectForm"
        :model="subjectForm"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-model-item :label="$t('all.autotext949')" prop="researchName">
          <a-input readOnly :value="subjectForm.researchName"></a-input>
        </a-form-model-item>
        <a-form-model-item :label="$t('all.autotext56')" prop="ptsName">
          <a-input :placeholder="$t('all.autotext282')" v-model="subjectForm.ptsName"></a-input>
        </a-form-model-item>
        <a-form-model-item :label="$t('all.autotext1357')" prop="ptsNo">
          <a-input :placeholder="$t('all.autotext57')" v-model="subjectForm.ptsNo"></a-input>
        </a-form-model-item>
        <a-form-model-item
          :label="$t('all.autotext1053')"
          prop="ptsPhone"
          :rules="[
            { required: !guardianChecked, message: $t('all.autotext396'), trigger: 'change' },
            { validator: validatePass, trigger: 'blur' }
          ]"
        >
          <a-input :placeholder="$t('all.autotext396')" v-model="subjectForm.ptsPhone"></a-input>
        </a-form-model-item>
        <a-form-model-item :label="$t('subject.autotext2')" class="switch">
          <a-switch v-model="guardianChecked" @change="handleGuardianCheckSwitch"></a-switch>
        </a-form-model-item>
        <template v-if="guardianChecked">
          <a-form-model-item :label="$t('subject.autotext3')" required prop="guardianName">
            <a-input :placeholder="$t('subject.autotext5')" v-model="subjectForm.guardianName"></a-input>
          </a-form-model-item>
          <a-form-model-item :label="$t('subject.autotext4')" required prop="guardianPhone">
            <a-input :placeholder="$t('subject.autotext6')" v-model="subjectForm.guardianPhone"></a-input>
          </a-form-model-item>
          <a-form-model-item :label="$t('all.autotext1492')" prop="guardianRelation">
            <a-select v-model="subjectForm.guardianRelation" :placeholder="$t('all.autotext1492')">
              <a-select-option v-for="(item, index) in $const.RELATION_TYPE" :key="index" :value="item.value">{{ item.desc }}</a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item :label="$t('subject.autotext37')">
            <a-upload
              name="file"
              accept=".pdf, .jpg, .jpeg, .png"
              :file-list="fileList"
              :customRequest="handleCustom"
              @change="handleChange"
            >
              <a-button :disabled="fileList.length>0">{{ $t('all.autotext565') }}</a-button>
            </a-upload>
            <!-- <a-button class="download" type="primary" @click="handleDownloadProve">{{ $t('all.autotext626') }}</a-button> -->
          </a-form-model-item>
        </template>
        <a-form-model-item
          class="form-code"
          :label="$t('all.autotext452')"
          required
          prop="verifyCode"
        >
          <a-input
            class="code-input"
            :placeholder="$t('all.autotext639')"
            v-model="subjectForm.verifyCode"
            :maxLength="6"
          >
          </a-input>
          <a-button
            class="code-btn"
            type="link"
            @click="getMessage"
            :disabled="countDownSeconds !== 0"
          >
            {{  countDownSeconds ? `${countDownSeconds} ${$t('all.autotext1161')}` : $t('all.autotext1151') }}
          </a-button>
        </a-form-model-item>
      </a-form-model>
      <div class="agreen">
        <a-checkbox @change="onChange" :checked="check">
          {{ $t('all.autotext1438.1') }}<a :href="privacyUrl" target="_blank">《{{ $t('all.autotext1438.2') }}》</a>
        </a-checkbox>
      </div>
    </div>
    <div class="wx-invite__footer">
      <a-button
        size="large"
        type="primary"
        @click="submit"
        :loading="submitLoading"
      >
        {{ $t('all.autotext794') }}
      </a-button>
    </div>
  </div>
</template>

<script>
import WeixinHeader from '@views/weixin/components/weixin-header.vue'
import { apiAddPtsForQrCode, apiGetMessage, ptsTypes, apiVerifyMessageCode } from '@api/overview/subject'
import { apiGetProStatus, uploadFile } from '@api/common'

export default {
  name: 'weixin-invite',
  components: { WeixinHeader },
  data () {
    let validateName = (rule, value, callback) => {
      if (!value) {
        callback()
      } else {
        if (!/^[\u4e00-\u9fa5]{2,4}$/.test(value)) {
          callback(new Error(this.$t('all.autotext487')))
        } else {
          callback()
        }
      }
    }
    return {
      fileList: [],
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      adminId: '',
      countDownSeconds: 0,
      countDownInterval: null,
      ptsTypes: [],
      proName: '',
      proNo: '',
      guardianChecked: false,
      submitLoading: false,
      subjectForm: {
        ptsName: '',
        ptsPhone: '',
        proId: '',
        researchId: '',
        researchName: '',
        ptsTypeRoleId: undefined,
        ptsNo: '',
        guardianName: '',
        guardianPhone: '',
        verifyCode: '',
        guardianRelation: ''
      },
      check: false,
      privacyUrl: location.origin + '/privacy?type=h5',
      rules: {
        researchName: [{ required: true, message: this.$t('all.autotext444'), trigger: 'change' }],
        ptsTypeRoleId: [{ required: true, message: this.$t('all.autotext142'), trigger: 'change' }],
        ptsName: [
          { required: true, message: this.$t('all.autotext282'), trigger: 'change' },
          { validator: validateName, trigger: 'blur' }
        ],
        ptsNo: [{ required: true, message: this.$t('all.autotext57'), trigger: 'change' }],
        guardian: [{ required: true, message: this.$t('all.autotext1490'), trigger: 'change' }],
        guardianRelation: [{ required: true, message: this.$t('all.autotext1348') + this.$t('all.autotext1492'), trigger: 'change' }],
        guardianName: [
          { required: true, message: this.$t('subject.autotext5'), trigger: 'change' },
          { validator: validateName, trigger: 'blur' }
        ],
        guardianPhone: [
          { required: true, message: this.$t('subject.autotext6'), trigger: 'change' },
          { validator: this.validatePass, trigger: 'blur' }
        ],
        verifyCode: [{ required: true, message: this.$t('all.autotext411'), trigger: 'change' }]
      }
    }
  },
  created () {
    this.getPtsTypes()
  },
  async mounted () {
    const { proId, researchId, adminId } = this.$route.query
    const result = await apiGetProStatus({ proId, researchId })
    if (result.errorType !== 0) {
      // todo： 用中文来判断状态太 shit 了，后面迭代能改就改吧
      const closedType = (result.errorType === 3 || result.errorType === 4) ? 1 : 2
      console.log('closedType', closedType)
      // this.$router.push({
      //   path: `/wx/invite-failed/${closedType}`
      // })
    } else {
      this.adminId = adminId
      this.proName = result.proName
      this.proNo = result.proNo
      this.subjectForm.proId = proId
      this.subjectForm.researchId = researchId
      this.subjectForm.researchName = result.orgName
    }
  },
  beforeDestroy () {
    clearInterval(this.countDownInterval)
  },
  methods: {
    handleCustom (file) {
      const params = new FormData()
      params.append('file', file.file)
      uploadFile(params).then(res => {
        file.onSuccess(res, file.file)
      }).catch(() => {
        this.fileList = []
        this.$message.error(this.$t('all.autotext1259'))
      }).finally(() => {})
    },
    handleChange ({ file, fileList }) {
      this.fileList = fileList
    },
    handleDownloadProve () {
      console.log('证明文件模板下载')
    },
    validatePass (rule, value, callback) {
      if (!value) {
        callback()
      } else {
        if (!/^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/.test(value)) {
          callback(new Error(this.$t('all.autotext544')))
        } else {
          callback()
        }
      }
    },
    handleGuardianCheckSwitch (checked) {
      if (checked) {
        // this.subjectForm.ptsPhone = ''
      } else {
        this.subjectForm.guardianPhone = ''
      }
    },
    async getPtsTypes () {
      const res = await ptsTypes({ proId: this.$route.query.proId })
      this.ptsTypes = res
    },
    getMessage () {
      const valid = () => {
        if (!this.subjectForm.ptsPhone && !this.subjectForm.guardianPhone) {
          this.$message.error(this.$t('all.autotext306'))
          return false
        }
        return true
      }
      if (!valid()) return
      const params = {
        phone: this.subjectForm.guardianPhone || this.subjectForm.ptsPhone
      }
      this.countDownSeconds = 59
      this.countDownInterval = setInterval(() => {
        this.countDownSeconds -= 1
        if (this.countDownSeconds === 0) {
          clearInterval(this.countDownInterval)
        }
      }, 1000)
      return apiGetMessage(params)
    },
    async verifyMessageCode () {
      let result = true
      try {
        await apiVerifyMessageCode({
          code: this.subjectForm.verifyCode,
          phone: this.subjectForm.guardianPhone || this.subjectForm.ptsPhone
        })
      } catch (e) {
        this.submitLoading = false
        result = false
      }
      return result
    },
    onChange (e) {
      this.check = e.target.checked
    },
    submit () {
      this.$refs.subjectForm.validate(async valid => {
        if (valid) {
          if (!this.check) {
            this.$message.error(this.$t('all.autotext1526'))
            return
          }
          this.submitLoading = true
          const passed = await this.verifyMessageCode()
          if (!passed) return
          const params = {
            type: 0, // 以前的逻辑------1-添加 2-添加并邀请关联小程序
            proId: this.subjectForm.proId,
            adminId: this.adminId, // 生成二维码
            proManagePtsList: JSON.stringify([Object.assign(
              this.subjectForm,
              {
                proveFileUrl: (this.guardianChecked && this.fileList.length > 0) ? this.fileList[0].response : '',
                guardianWechat: 0,
                ptsWechat: 0,
                ptsTypeRoleIdDesc: this.ptsTypes.find(e => e.id === this.subjectForm.ptsTypeRoleId)?.description
              }
            )])
          }
          apiAddPtsForQrCode(params).then((res = {}) => {
            console.log('res', res)
            this.$router.push({
              path: '/wx/invite-success',
              query: { ...res, guardianPhone: this.subjectForm.guardianPhone, ptsPhone: this.subjectForm.ptsPhone }
            })
          }).finally(() => {
            this.submitLoading = false
          })
        }
      })
    }
  }
}
</script>

<style scoped lang='less'>
.wx-invite {
  .wx-invite__content {
    background-color: #fff;
    padding-bottom: 16px;
    .sub-title {
      padding-left: 16px;
      font-size: 16px;
      height: 60px;
      line-height: 60px;
      border-bottom: 1px solid #F5F5F5;
      font-weight: 500;
    }
    .wx-invite__form {
      padding: 0 18px;
      /deep/.ant-form-item {
        margin: 0;
        padding: 10px 0;
        border-bottom: 1px solid #f5f5f5;
        display: flex;
        align-items: center;
      }
      /deep/.ant-form-item-label {
        padding: 0;
      }
      .guardianRelation-upload{
        /deep/ .ant-form-item-children{
          display: flex;
          justify-content: space-around;
          align-items: center;
        }
      }
      .ant-input {
        border: none;
        &:focus {
          border: none;
          box-shadow: none;
        }
      }
      /deep/ .ant-select-selection {
        border: none;
        .ant-select-selection__placeholder {
          color: #D6DFEC !important;
        }
      }
      /deep/.ant-form-explain {
        padding-left: 10px;
      }
      .code-input {
        width: 100px;
      }
      .switch {
        text-align: right;
      }
    }
  }
  /deep/.form-code {
  .ant-form-item-children {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .code-btn {
    padding: 0;
  }
}
  .wx-invite__footer {
    padding: 32px 0;
    text-align: center;
    .ant-btn {
      width: 50%;
      background-color: #263667;
      border-color: #263667;
    }
  }
}
.agreen {
  padding: 12px 20px 0;
}

</style>
